package com.sunnypower.rushfitapp.util;

import android.content.Context;
import android.content.SharedPreferences;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetData {

    private static String responseData = null;

    public static String doGet(String url) {
        final CountDownLatch latch = new CountDownLatch(1);
        //1.拿到OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2.构造Request
        Request.Builder builder = new Request.Builder();
        //Request request = builder.get().url("https://douban.uieee.com/v2/movie/in_theaters?start=0&count=20").build();
        //        "https://api.douban.com/v2/movie/top250?apikey=0df993c66c0c636e29ecbb5344252a4a&start=" + i + "&count=1"
        Request request = builder.get().url(url).build();

        //3.将Request封装为Call
        Call call = okHttpClient.newCall(request);
        // Response response = call.execute();
        //4.执行call
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                L.e("onFailure" + e.getMessage());
                e.printStackTrace();
                responseData="geterror";
                latch.countDown();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                L.e("onResponse");
                final String res = response.body().string();
                L.e(res);
                responseData = res;
                latch.countDown();
            }
        });
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return responseData;
    }


}
